import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:zrjz/api/auth_repository.dart';
import 'package:zrjz/comm/constants/app_constant.dart';
import 'package:zrjz/comm/http/http_result.dart';
import 'package:zrjz/comm/utils/event_bus.dart';
import 'package:zrjz/comm/utils/ext_dart.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/comm/utils/util.dart';

import 'reset_password_state.dart';

class ResetPasswordController extends GetxController {
  final ResetPasswordState state = ResetPasswordState();
  final AuthRepository authRepository = Get.find();

  bool isChangedType = false;
  String? oldPasswordErrorText; //表单的错误信息展示
  String? passwordErrorText;
  String? confirmPasswordErrorText;

  String? oldPsd;
  String? password;
  String? confirmPsd;

  /// 执行手机号码的绑定
  void doResetPassword() {
    oldPasswordErrorText = null;
    passwordErrorText = null;
    confirmPasswordErrorText = null;
    update();

    var oldPsdController = state.formData['old_password']!['controller'];
    var passwordController = state.formData['password']!['controller'];
    var confirmPsdController = state.formData['confirm_password']!['controller'];

    oldPsd = oldPsdController.text;
    password = passwordController.text;
    confirmPsd = confirmPsdController.text;

    Log.d('oldPsd:$oldPsd password:$password confirmPsd:$confirmPsd');

    if (Utils.isEmpty(oldPsd) && isChangedType) {
      oldPasswordErrorText = "旧密码不能为空";
      update();
    } else if (Utils.isEmpty(password)) {
      passwordErrorText = "新密码不能为空";
      update();
    } else if (Utils.isEmpty(confirmPsd)) {
      confirmPasswordErrorText = "确认新密码不能为空";
      update();
    } else if (password != confirmPsd) {
      confirmPasswordErrorText = "确认密码不一致，请检查密码";
      update();
    } else {
      _requestForgetPsd();
    }
  }

  /// 请求接口，普通的密码注册
  void _requestForgetPsd() async {
    // //获取到数据
    // SmartDialog.showLoading();
    //
    // HttpResult result;
    // if (isChangedType) {
    //   result = await authRepository.changePassword(oldPsd, password, confirmPsd);
    // } else {
    //   result = await authRepository.setPassword(password, confirmPsd);
    // }
    //
    // SmartDialog.dismiss(status: SmartStatus.loading);
    //
    // //处理数据
    // if (result.isSuccess) {
    //   SmartDialog.showNotify(msg: isChangedType ? '修改密码成功'.tr : '设置密码成功'.tr, notifyType: NotifyType.success);
    //
    //   //发送通知刷新用户详情信息
    //   bus.emit(AppConstant.eventProfile2Refresh, true);
    //
    //   //成功了返回
    //   Get.back();
    // } else {
    //   _handleErrorMessage(result);
    // }
  }

  /// 处理网络请求注册的表单错误
  void _handleErrorMessage(HttpResult<dynamic> result) {
    String? errorMessage = result.errorMsg;
    SmartDialog.showToast(errorMessage ?? '修改出错误了');

    Map<String, dynamic>? json = result.getErrorJson();
    handleFormError(json, 'old_password', (str) {
      oldPasswordErrorText = str;
    });
    handleFormError(json, 'password', (str) {
      passwordErrorText = str;
    });
    handleFormError(json, 'password_confirmation', (str) {
      confirmPasswordErrorText = str;
    });
  }

  // =========================== 焦点控制 ===========================

  FocusNode? _oldPsdFocusNode;
  FocusNode? _passwordFocusNode;
  FocusNode? _confirmPsdFocusNode;

  void _onPhoneFocusChange() {
    if (_oldPsdFocusNode?.hasFocus == true) {
      oldPasswordErrorText = null;
      update();
    }
  }

  void _onPasswordFocusChange() {
    if (_passwordFocusNode?.hasFocus == true) {
      passwordErrorText = null;
      update();
    }
  }

  void _onNewPasswordFocusChange() {
    if (_confirmPsdFocusNode?.hasFocus == true) {
      confirmPasswordErrorText = null;
      update();
    }
  }

  @override
  void onInit() {
    super.onInit();
    _oldPsdFocusNode = state.formData['old_password']!['focusNode'];
    _passwordFocusNode = state.formData['password']!['focusNode'];
    _confirmPsdFocusNode = state.formData['confirm_password']!['focusNode'];

    isChangedType = Get.arguments['type'] == 'change';
    update();
  }

  @override
  void onReady() {
    super.onReady();
    _oldPsdFocusNode?.addListener(_onPhoneFocusChange);
    _passwordFocusNode?.addListener(_onPasswordFocusChange);
    _confirmPsdFocusNode?.addListener(_onNewPasswordFocusChange);
  }

  @override
  void onClose() {
    super.onClose();
    _oldPsdFocusNode?.removeListener(_onPhoneFocusChange);
    _passwordFocusNode?.removeListener(_onPasswordFocusChange);
    _confirmPsdFocusNode?.removeListener(_onNewPasswordFocusChange);
    _oldPsdFocusNode = null;
    _passwordFocusNode = null;
    _confirmPsdFocusNode = null;
  }

  bool valid(String text) {
    final isValid = RegExp(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$').hasMatch(text);
    return isValid;
  }
}
